import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

const router = new VueRouter({
  routes: [
    {
      name: 'login',
      path: '/login',
      component: () => import('@/views/login.vue')
    },
    {
      name: 'index',
      path: '/index',
      component: () => import('@/views/index.vue'),
      // 添加重定向
      redirect: { name: 'welcomeYou' },
      // 使用children设置嵌套路由
      children: [
        {
          name: 'welcomeYou',
          path: 'welcomeYou',
          component: () => import('@/views/welcomeYou.vue')
        },
        {
          name: 'postList',
          path: 'postList',
          component: () => import('@/views/postList.vue')
        },
      ]
    }
  ]
});

import { Message } from 'element-ui';
// 添加导航守卫，除了登录之外的所有页面都需要进行token的验证
router.beforeEach((to, from, next) => {
  console.log(to);
  if (to.name == 'login') {
    next();
  } else {
    let token = JSON.parse(localStorage.getItem('hm_toutiao_houtai') || '{}').token;
    if (token) {
      next();
    } else {
      next({ path: '/login' });
      Message.error("请先登录");
    }
  }
});

export default router;